package com.zbkj.crmeb.order.channel;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.zbkj.crmeb.enums.ProductTypeEnum;
import com.zbkj.crmeb.plat.by.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.crmeb.core.common.CommonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.utils.PriceUtil;
import com.crmeb.core.config.RestTemplateConfig;
import com.zbkj.crmeb.enums.PurchaseOrderChannelTypeEnum;
import com.zbkj.crmeb.order.AbstractStoreOrderService;
import com.zbkj.crmeb.order.StoreOrderFactory;
import com.zbkj.crmeb.order.request.BellettiniOrderRequest;
import com.zbkj.crmeb.order.response.BellecttiniOrderResponse;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreProductAttrValue;
import com.zbkj.crmeb.store.service.StoreProductAttrValueService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.store.vo.StoreOrderInfoVo;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@Service
public class BellettiniStoreOrderServiceImpl extends AbstractStoreOrderService {
    @Resource
    private StoreOrderDao storeOrderDao;
    @Autowired
    RestTemplateConfig restTemplateConfig;
    @Autowired
    StoreProductService storeProductService;
    @Autowired
    StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    PriceUtil priceUtil;
    @Autowired
    StoreOrderFactory storeOrderFactory;

    /********* bellettini配置参数  *********/
    @Value("${bellettini.url}")
    private String bellettiniUrl;
    @Value("${bellettini.key}")
    private String bellettiniKey;
    @Value("${bellettini.type}")
    private String bellettiniType;

    @Override
	public CommonResult<Object> addChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        List<String> errorMessages = new ArrayList<>();  // 用于收集错误信息
		try {
		    // TODO didiok
			int num = 1;
			for (StoreOrderInfoVo order : orderInfoVoList) {
				StoreProductAttrValue attrValue = order.getInfo().getProductInfo().getAttrInfo();
				String sourceSkuId = attrValue.getSourceSkuId();
				if(sourceSkuId.startsWith(ProductTypeEnum.BELLETTINI.getCode()+"-")){
                    sourceSkuId = sourceSkuId.replaceFirst(ProductTypeEnum.BELLETTINI.getCode()+"-","");
                }
				// 组建订单对象
				BellettiniOrderRequest request = new BellettiniOrderRequest();
				if(9 != storeOrder.getSource()) {
                    storeOrder.setPushOrderNo(order.getChildOrderNumber()+ "-" + num);
				}
				request.setOrderNumber(storeOrder.getPushOrderNo()).setSkuSize(sourceSkuId)
						.setQuantity(order.getInfo().getCartNum().toString()).setZone("EXTRA_CEE")
						.setPartnerPrice(priceUtil.rmb2EurStatic(attrValue.getSourceCost(),order.getExchangeRate()).toString());
                Result result = pushOrder(storeOrder, request, order);
                // 如果推单错误
                if(!result.isSuccess()){
                    errorMessages.add("订单号: " + order.getOrderInfoId() + ",错误: " + result.getMessage());
                }
                num++;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

        if (!errorMessages.isEmpty()) {
            return CommonResult.failed(String.join("\n", errorMessages));
        }
		return CommonResult.success();
	}

    private Result pushOrder(StoreOrder storeOrder, BellettiniOrderRequest request, StoreOrderInfoVo orderInfo) throws Exception {
        // 组装请求url
        StringBuilder sb = new StringBuilder();
        sb.append(bellettiniUrl);
        HttpHeaders headers = new HttpHeaders();
        headers.add("x-api-key", bellettiniKey);
        headers.add("Content-Type", bellettiniType);
        //处理请求参数
        MultiValueMap<String,Object> map = new LinkedMultiValueMap<>();
        map.add("order_number",request.getOrderNumber());
        map.add("sku_size",request.getSkuSize());
        map.add("quantity",request.getQuantity());
        map.add("partner_price",request.getPartnerPrice());
        map.add("zone",request.getZone());
        HttpEntity< MultiValueMap<String,Object>> requestEntity = new HttpEntity<>(map, headers);
        RestTemplate restTemplate = restTemplateConfig.restTemplate();
        log.info("--------------- 开始请求Bellettini创建订单url: {};请求参数:{} ---------------", sb,map.toString());
        ResponseEntity<String> response = restTemplate.postForEntity(sb.toString(), requestEntity, String.class);
        log.info("--------------- 请求Bellettini创建订单返回结果: {} ---------------", response);
        if (HttpStatus.OK != response.getStatusCode()) {
            JSONObject message = JSONObject.parseObject(response.getBody());
            String errorMessage = message.getString("error");
            log.info("--------------- {} ---------------", errorMessage);
        }
        //处理返回结果
        ObjectMapper mapper = new ObjectMapper();
        BellecttiniOrderResponse bellecttiniOrderResponse = mapper.readValue(response.getBody(), BellecttiniOrderResponse.class);
        String message = bellecttiniOrderResponse.getMessage();
        if (bellecttiniOrderResponse.getCode() == 0) {
			// 新增采购单
			storeOrderFactory.insertPurchaseOrder(storeOrder, true, PurchaseOrderChannelTypeEnum.BELLETTINI.getCode());
			// 新增采购商品
			String sn = bellecttiniOrderResponse.getOrder().getOrder_number();
            // TODO didiok
			storeOrderFactory.insertPurchaseGoods(orderInfo, storeOrder, true, bellecttiniOrderResponse.getMessage(), sn);
			if (storeOrder.getPushStatus() != 2) {
				StoreOrder storeOrderUpdate = new StoreOrder();
				storeOrderUpdate.setId(storeOrder.getId());
				storeOrderUpdate.setPushStatus(1);
				storeOrderUpdate.setPushMessage("BELLETTINI推送:" + bellecttiniOrderResponse.getMessage());
				storeOrderDao.updateById(storeOrderUpdate);
				log.info("--------------- BELLETTINI下订单成功:{},商品id:{} ---------------", bellecttiniOrderResponse.getMessage(),
						orderInfo.getProductId());

			}
            return new Result(true, null, message);
		}else {
			// 新增采购单
			storeOrderFactory.insertPurchaseOrder(storeOrder, false, PurchaseOrderChannelTypeEnum.BELLETTINI.getCode());
			// 新增采购商品
			storeOrderFactory.insertPurchaseGoods(orderInfo, storeOrder, false, bellecttiniOrderResponse.getMessage(), null);
			StoreOrder storeOrderUpdate = new StoreOrder();
			storeOrderUpdate.setId(storeOrder.getId());
			storeOrderUpdate.setPushStatus(2);
            storeOrderUpdate.setPushMessage(bellecttiniOrderResponse.getMessage());
            storeOrderDao.updateById(storeOrderUpdate);
            log.info("--------------- 下订单失败:{},商品id:{} ---------------", bellecttiniOrderResponse.getMessage(), orderInfo.getProductId());
            return new Result(false, null, message);
        }
    }

    @Override
    public CommonResult<Object> cancelChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        return null;
    }

    @Override
    public CommonResult<Object> getOrderInfo(String channelOrderSn) {
        return null;
    }
}
